'use strict';
import { merchantApplyWineRecordsModel } from "../model/merchantApplyWineRecords";
import { merchant_wineService } from "../service/merchant_wine";
import { ServiceBase, Exceptions } from '../kalend';
import { merchantService } from "./merchant";
import { ObjectId } from "bson";
import _ = require("underscore");
var moment = require('moment');

class MerchantApplywineService extends ServiceBase {
    constructor() {
        super(merchantApplyWineRecordsModel)
    }
    async query(params: any) {
        const offset = params.offset || 1;
        const limit = params.limit || 15;
        const mid = params.mid;
        const sendstatus = params.sendstatus;
        const auditstatus = params.auditstatus;
        const starttime = params.sdate;
        const endtime = params.edate;
        const agentid = params.agentid;
        const name = params.name;
        let filter: any = {};

        if (starttime) {
            filter.updateTime = { '$gte': new Date(moment(new Date(starttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (endtime) {
            if (filter.updateTime) {
                filter.updateTime['$lte'] = new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.updateTime = { '$lte': new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }
        if (sendstatus == 0 || sendstatus == 1) {
            filter.SendStatus = sendstatus;
        }
        if (auditstatus == 0 || auditstatus == 1 || auditstatus == 2) {
            filter.AuditStatus = auditstatus;
        }
        if (mid) {
            filter.merchantid = mid;
        }
        if (agentid) {
            filter.AgentId = agentid;
        }
        if (name) {
            const merdata = await merchantService.queryAlls({ name: { $regex: name, $options: 'i' } });
            if (merdata && merdata.length > 0) {
                const merid = merdata.map((a) => {
                    return a._id;
                });
                filter.merchantid = { $in: merid };
            }
        }

        let data = await super.queryPagination(offset, limit, {
            filter: filter
        });
        data.rows = data.rows.map((item) => {

            //let merc:any= await merchantService.querySingle({_id:item.merchantid});

            //item.merchantname=merc.name;

            if (item.updateTime) {
                item.updateTime = moment(item.updateTime).format('YYYY-MM-DD HH:mm');
            }
            if (item.AuditStatus == '0') {
                item.AuditStatus = '未审核';
            } else if (item.AuditStatus == '1') {
                item.AuditStatus = '已审核';
            } else if (item.AuditStatus == '2') {
                item.AuditStatus = '审核拒绝';
            }

            if (item.SendStatus == '0') {
                item.SendStatus = '未配送';
            } else if (item.SendStatus == '1') {
                item.SendStatus = '已配送';
            }
            if (item.merchantid) {
                item.mername = item.merchantid.name;
            }
            return item;
        });
        return data;
    }

    async queryall(params: any) {
        return this.queryAll({
            filter: { merchantid: params.merchantid }
        });
    }

    async audit(doc: any) {
        const audits = doc.AuditStatus;
        const sends = doc.SendStatus;
        if (audits) {
            return this.update(doc._id, { AuditStatus: audits });
        }

        if (sends == 1) {

            //更新商户酒水库存
            let onem: any = await this.querySingle({ _id: doc._id });
            if (onem.winelist) {
                for (let index = 0; index < onem.winelist.length; index++) {
                    const element = onem.winelist[index];
                    let onewine: any = await merchant_wineService.querySingle({ _id: element._id, merchantid: onem.merchantid });

                    let totalstock = Number(onewine.stock) + Number(element.count);
                    await merchant_wineService.update(onewine._id, {
                        stock: totalstock
                    })
                }
            }
            return this.update(doc._id, { SendStatus: sends });
        }
    }

    async save(doc: any) {
        if (doc._id) {
            return this.update(doc._id, doc);
        } else {
            return this.create(doc);
        }
    }

    async queryAlls(filter: any) {
        return this.queryAll({
            filter: filter
        });
    }

    async queryWineApply(mid: any) {
        let data = await merchantApplyWineRecordsModel.aggregate([
            {
                $match: { AuditStatus: { $in: [0, 1] }, merchantid: new ObjectId(mid) }
            },
            {
                $group: {
                    "_id": null,
                    "total": {
                        "$sum": "$totalcount"
                    }
                }
            },
            {
                $project: {
                    "_id": 0,
                    "total": 1
                }
            }
        ]);
        if (data && data.length > 0) {
            return data[0].total;
        } else {
            return 0;
        }
    }

    async queryWineApplyByMid(mid: any) {
        const data = await this.queryAll({ filter: { merchantid: mid }, select: 'winelist totalcount' });
        let winelist: Array<any> = [];
        data.forEach((item) => {
            winelist = _.union(winelist, item.winelist);
        });
        winelist = winelist.filter((a) => {
            return a.count && Number(a.count) > 0;
        });
        return winelist;
    }

    async queryByid(id: any){
        let data= await this.querySingle({_id: id});
        let wines = (await merchant_wineService.querybymerchantid({mid: data.merchantid})).rows;
        data.winelist.forEach((item:any) => {
            const winedata= wines.find((a)=>{
                return a._id.toJSON()== item.wineid;
            });
            if(winedata){
                item.img= winedata.img;
                item.name= winedata.winename;
            }
        });
        return data;
    }


}

export const merchantapplywineService = new MerchantApplywineService();